package com.xu.ai.chatclient.service;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import com.xu.ai.chatclient.util.AiRestUtil;

/**
 * @author xuguan
 * @since 2025/10/17
 */
@Service
public class RestClientService {

	private static final Logger log = LoggerFactory.getLogger(RestClientService.class);

	private final String apiKey;

	private final RestClient restClient;

	private final ObjectMapper objectMapper;

	public RestClientService(@Value("${spring.ai.dashscope.api-key}") String apiKey,
			RestClient.Builder restClientBuilder, ObjectMapper objectMapper) {
		this.apiKey = apiKey;
		this.restClient = restClientBuilder.baseUrl("https://dashscope.aliyuncs.com").build();
		this.objectMapper = objectMapper;
	}

	public DashScopeApi.ChatCompletion send(AiRestUtil.ModelUri modelUri, Object body, boolean enableAsync) {
		String requestBody;
		if (body instanceof String str) {
			requestBody = str;
		}
		else {
			try {
				requestBody = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
			}
			catch (JsonProcessingException e) {
				throw new RuntimeException(e);
			}
		}
		log.info("uri: {}, requestBody: {}", modelUri.getUri(), requestBody);
		final ResponseEntity<DashScopeApi.ChatCompletion> responseEntity = restClient.post()
			.uri(modelUri.getUri())
			.headers(headers -> {
				headers.setContentType(MediaType.APPLICATION_JSON);
				headers.setBearerAuth(apiKey);
				if (enableAsync) {
					// 异步处理配置参数
					headers.add("X-DashScope-Async", "enable");
				}
			})
			.body(body)
			.retrieve()
			.toEntity(DashScopeApi.ChatCompletion.class);
		final DashScopeApi.ChatCompletion responseBody = responseEntity.getBody();
		try {
			log.info("responseBody: {}",
					objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(responseBody));
		}
		catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
		return responseBody;
	}

}
